package com.xes.apps.ams.utils;

import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.UriTemplate;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;

public class HttpClientUtil {
	private static final Logger log = LogManager.getLogger(HttpClientUtil.class);

	public static String httpGet(String url, Header[] headers, List<NameValuePair> params) {
		String result = "";
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			HttpGet httpGet = null;
			if (CollectionUtils.isEmpty(params)) {
				httpGet = new HttpGet(url);
			} else {
				String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
				httpGet = new HttpGet(url + "?" + str);
			}
			if (headers != null) {
				httpGet.setHeaders(headers);
			}
			httpclient = HttpClients.createDefault();
			log.info("GET===before=====================response==="+response);
			response = httpclient.execute(httpGet);
			log.info("GET===after=====================response==="+response);
			HttpEntity entity = response.getEntity();
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(entity);
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			log.error("Can't send httpget: " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send httpget: " + e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error("Can't send httpget: " + e.getMessage(), e);
		} finally {
			if (null != httpclient)
				try {
					httpclient.close();
				} catch (IOException e) {
					log.error("Can't send httpget: " + e.getMessage(), e);
				}
			if (null != response) {
				try {
					response.close();
				} catch (IOException e) {
					log.error("Can't send httpget: " + e.getMessage(), e);
				}
			}
		}
		return result;
	}
	
	public static String httpPost(String url, Header[] headers, List<NameValuePair> params) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length() > 0, "url is:\'\'");
			HttpPost httppost = new HttpPost(url);
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
			entity.setChunked(true);
			httppost.setEntity(entity);
			httppost.setHeaders(headers);
			httpclient = HttpClients.createDefault();
			System.out.println("POST===before====================================response:"+response);
			response = httpclient.execute(httppost);
			System.out.println("POST===after====================================response:"+response);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				body = EntityUtils.toString(response.getEntity());
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			log.info("Can't send sendPost... " + e.getMessage(), e);
		} catch (IOException e) {
			log.info("Can't send sendPost... " + e.getMessage(), e);
		} catch (Throwable e) {
			log.info("Can't send sendPost... " + e.getMessage(), e);
		} finally {
			if (null != httpclient)
				try {
					httpclient.close();
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
			if (null != response)
				try {
					response.close();
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
		}
		return body;
	}
	
	public static String httpPost(String url, String jsonStr) {
		String body = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			Preconditions.checkArgument(url.length()>0, "url is:\'\'");
			HttpPost httppost = new HttpPost(url);
			StringEntity StringEntity = new StringEntity(jsonStr,Consts.UTF_8);
			httppost.setEntity(StringEntity);
			Header[]  headers =  new BasicHeader[]{new BasicHeader("Content-Type", "application/json")}; 
			httppost.setHeaders(headers);
			httpclient = HttpClients.createDefault();
			response = httpclient.execute(httppost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				body=EntityUtils.toString(response.getEntity());
			}else{
				log.info(response.toString());
			}
			EntityUtils.consume(StringEntity);
		} catch (ClientProtocolException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		} catch (IOException e) {
			log.error("Can't send sendPost... " + e.getMessage(), e);
		}catch(IllegalArgumentException e){
			log.error("Can't send sendPost... " + e.getMessage(), e);
		}finally {
			if (null != httpclient)
				try {
					httpclient.close();
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
			if (null != response)
				try {
					response.close();
				} catch (IOException e) {
					log.error("Can't send sendPost... " + e.getMessage(), e);
				}
		}
		return body;
	}
	
	
	public static void main(String[] args) {
		String url = "http://localhost:8080/amsclient/card/query/{cardNum}";
		Map<String, String> vars = ImmutableMap.of("cardNum", "001001016076337");
		URI expandUri = new UriTemplate(url).expand(vars);
		String respStr = httpGet(expandUri.toString(), null, null);
		System.out.println(respStr);
	}
}
